#!/usr/bin/python

from werkzeug import Response, redirect
from utils import render_template, expose, url_for, jsonify
from .. import config, format

persist = {}

@expose('/config')
@expose('/')
def configuration(request):
  return render_template('config.html', request=request,
                         config=config.config_lines, loaded=config.loaded,
                         write_back=config.config_file,
                         persist=persist.get('config', {}))

@expose('/compare')
def compare(request):
  return render_template('compare.html', request=request,
                         linkspecs=config.linkspecs,
                         persist=persist.get('compare', {}))

@expose('/evaluate')
def evaluate(request):
  return render_template('evaluate.html', request=request)

@jsonify
@expose('/load_config')
def load_config(request):
  try:
    config.load(request.form.get('config_file'), is_file=False)
    if request.form.get('write', False):
      config.save()
      persist['config'] = request.form
  except config.Error, e:
    return { 'error': e.message }
  return { 'success': 1 }

@jsonify
@expose('/do_compare')
def do_compare(request):
  persist['compare'] = request.form

  # extract form values
  resource_pairs = request.form.get('resource_pairs').split('\n')
  #links_graph = rdflib.ConjunctiveGraph()
  #links_graph.parse(request.form.get('resource_pairs'), format='nt')


  reverse = request.form.get('reverse', False)
  linkspec_id = request.form.get('linkspec_id')

  # check LinkSpec ID
  if linkspec_id not in config.linkspecs:
    return { 'error': 'LinkSpec "%s" does not exist!' % linkspec_id }

  # set initial statistics values
  high = 0.0
  low = 1.0
  sum = 0.0
  num_exceptions = 0

  # compare link pairs
  links = []
  for pair in resource_pairs:
    # ignore empty lines
    if not pair.strip():
      continue
    try:
      # TODO: parse real NT format, not this bogus one
      src_resource, link, dst_resource = pair.strip().split(' ')
      src_resource = src_resource.strip('<> ')
      dst_resource = dst_resource.strip('<> ')
    except Exception:
     return { 'error': 'Resource pair "%s" is not formatted correctly' % pair }

    trace = {}

    # switch dst/src order if reverse checkbox is on
    if reverse:
      src_resource, dst_resource = dst_resource, src_resource

    # compare resource pair
    similarity = config.linkspecs[linkspec_id].compare_pair(src_resource,
                                                            dst_resource,
                                                            trace)

    # update statistics
    if similarity is None:
      num_exceptions += 1
      similarity = 0

    if similarity > high:
      high = similarity
    if similarity < low:
      low = similarity
    sum += similarity 

    links.append({
      'similarity': similarity,
      'trace': format.html.format([trace]),
      'src': src_resource,
      'dst': dst_resource
    })

  avg = sum / len(resource_pairs)

  return {
    'links': links,
    'high': str(high),
    'low': str(low),
    'avg': str(avg),
    'num_exceptions': num_exceptions
  }

def not_found(request):
    return render_template('not_found.html')
